<?php

namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\PackageDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\Equip;
use App\Models\Game\PackageRecord;
use App\Models\Game\RoleIds;
use App\Models\Game\Server;
use App\Services\Game\PackageService;
use App\Services\Game\UserMemberService;
use App\Services\Game\UserRoleService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class PackageController extends Controller //邮件
{
    private PackageService $packageService;
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * PackageController constructor.
     * @param PackageService $packageService
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(PackageService $packageService, UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->packageService = $packageService;
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }


    public function checkSendItemFormat() {
        try{
            $input = request()->all();
            $value = data_get($input,'value');
            $rows = explode("\n",$value);
            $results = [];
            $newRows = [];
            foreach($rows as $row){
                $b = preg_match("/^(\d+)?:(\d+):([0-1])$/",trim($row),$arr);
                $newRows[] = trim($row);
                if (!$b) throw new \Exception('格式错误');
                $id = $arr[1]; $num = $arr[2];  $isBind = $arr[3];
                $equip  = Equip::query()->where('id',$id)->first();
                if (!$equip) throw new \Exception("物品ID:$id 不存在");
                $results[] = [
                    "id"=>$id,
                    "number"=>$num,
                    "itemName"=>data_get($equip,'name'),
                    'isBind'=>$isBind?1:0 //是否绑定
                ];
            }
            $data = [
                'newText'=>join("\n",$newRows),
                'results'=>$results,
            ];
            return ResponseUtil::success($data);

        }catch(\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    private function itemTextToJsonStr($text){
        $array = [];
        $rows = explode("\n",$text);
        foreach($rows as $row){
            $b = preg_match("/^(\d+)?:(\d+)?:([0-1])$/",trim($row),$arr);
            if (!$b) throw new \Exception('格式错误1');
            $id = $arr[1]; $num = $arr[2]; $isBind = $arr[3];
            $equip = Equip::query()->where('id',$id)->first();
            $itemName = data_get($equip,'name');
            $array[] = [
                'itemId'=>$id,
                'number'=>$num,
                'isBind'=>$isBind,
                'itemName'=>$itemName,
            ];
        }
        return $array;
    }

    private function coinTextToJsonStr($text){
        $list = [];
        $strs = explode("\n",$text);
        foreach($strs as $row){
            $b = preg_match("/^(\d+)?:(\d+)$/",trim($row),$arr);
            if (!$b) throw new \Exception('格式错误');
            $type = $arr[1]; $number = $arr[2];
            $list[] = [
                'coinType'=>$type,
                'number'=>$number
            ];
        }
        if (count($list) > 6 ){
            throw new \Exception('最多5种货币');
        }
        return $list;
    }

    public function add(){ //邮件发送接口
        try {

            $input = request()->all(); $insert = [];
            $countDown = data_get($input,'countDown'); //倒计时发送
            $itemText = data_get($input,"itemText");
            $coinText = data_get($input,"coinText");
            $object = data_get($input,"object"); //object 0=全部,1=指定对象,2=限制等级
            $createDateTimeBegin = data_get($input,"createDateTimeBegin");
            $createDateTimeEnd = data_get($input,"createDateTimeEnd");
            $moneyMax = data_get($input,"moneyMax");
            $moneyMin= data_get($input,"moneyMin");
            $levelMin = data_get($input,"levelMin");
            $levelMax = data_get($input,"levelMax");
            $roleIdsStr = data_get($input,"roleIdsStr");
            $insert['title'] =  data_get($input,'title');
            $insert['content'] =  data_get($input,'content');
            $gameAreas = data_get($input,'gameAreas');
            if (empty($gameAreas)){
                return ResponseUtil::error('请选择区服');
            }
            $insert['object'] = $object;
            if ($object == 1) { //指定角色
                if (count($gameAreas) != 1){
                    throw new \Exception("指定角色时,区服必须且只能选择1个");
                }
                $roleIds = strArrToIntArr(explode(',',$roleIdsStr));
                global $gameArea; $gameArea = $gameAreas[0];
                $userRoles = $this->userRoleService->getByIds($roleIds,['id','nick','memid']);
                $roles = [];
                foreach($roleIds as $roleId) {
                    $gameRole = collect($userRoles)->where('id',$roleId)->first();
                    if (!$gameRole){
                        throw new \Exception("此角色不存在");
                    }
                    array_push($roles,[
                        'id'=>$roleId,
                        'nick'=>data_get($gameRole,'nick'),
                    ]);
                }
                $insert['roles'] = json_encode($roles);
            } else if ($object==2){ //指定范围
                if (!$levelMin || !$levelMax){
                    throw new \Exception("等级范围不正确");
                }
                $insert['level_range'] = $levelMin.",".$levelMax;
            }
            $insert['auth_status'] = $insert['send_status'] = 0;
            $insert['game_areas'] = json_encode($gameAreas);

            $packageNum = 0;//发送物品加货币的条数
            if ($itemText){
                $itemArr = $this->itemTextToJsonStr($itemText);
                $packageNum += count($itemArr);
                $insert['item'] = json_encode($itemArr);
            }
            if ($coinText){
                $coinArr = $this->coinTextToJsonStr($coinText);
                $packageNum += count($coinArr);
                $insert['coin'] = json_encode($coinArr);
            }
            if ($packageNum>14){
                throw new \Exception('物品加货币数据条目不能大于14');
            }
            $insert['create_time'] = time();
            if ($countDown){
                $insert['count_down'] = $countDown;
            }
            $insert['createDateTimeBegin'] = $createDateTimeBegin;
            $insert['createDateTimeEnd'] = $createDateTimeEnd;
            $insert['MailType_RMB_Max'] =$moneyMax;
            $insert['MailType_RMB_Min'] = $moneyMin;



            $b = PackageRecord::query()->insert($insert);
            if ($b){
                return ResponseUtil::success();
            }
        }catch(\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
        return ResponseUtil::error('写入失败');
    }

    public function auth($id){ //邮件发送审核
        $record = PackageRecord::query()->find($id);
        DB::beginTransaction();
        try{
            if ($record->auth_status!=0) {
                return ResponseUtil::error('无需重审');
            }
            $record->auth_status = 1;
            $record->auth_time = time();
            $record->save();
            if (!$record->count_down){ //非定时任务
                $this->packageService->sendEmailById($id);
            }
            DB::commit();
            return ResponseUtil::success();
        } catch(\Exception $e){
            DB::rollBack();
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function noauth($id){ //拒绝审核
        $record = PackageRecord::query()->find($id);
        $record->auth_status = -1;
        $record->auth_time = time();
        $record->save();
        return ResponseUtil::success();
    }

    public function paginate(){ //邮件发送记录查询列表 receiver,packageContent
        $paginate = $this->packageService->paginate(new PackageDTO(request()->all()));
        $data = $paginate->items();
        foreach($data as &$item){
            $item['receiver'] = ""; //接收者
            $item['packageContent'] = "";//礼包内容
            switch($item->object) {
                case 0: //全区
                    $game_areas = data_get($item,'game_areas',[]); //game_areas 是字段
                    $codes = join(',',$game_areas);
                    $item['receiver'] = $codes."区所有角色";
                    break;
                case 1: //指定对象
                    $userRoles = $item->roles;
                    foreach($userRoles as $role) {
                        $item['receiver'] .= "{$role['id']}:{$role['nick']}<br/>";
                    }
                    break;
                case 2: //限制等级
                    $item['receiver'] = "限定等级:".$item->level_range; //接收者
                    break;
            }
        }
        $res =[];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return $res;
    }



    public function sendText() {
        MyLog::info('开始执行批量发送');

        $jsonString = '{"QueryType":0,"MailPid":7881,"MailTitle":"系统邮件","MailContent":"合服龙腾经验补发","SenderName":"系统","AttaItems":[{"Id":3000074,"Amount":46,"IntensifyLv":0,"GemHoleCount":0,"IsBinding":1,"AddiAttr":null,"OreAddiAttr":null,"GemAttr":null}],"AttaMoney":null}';
        // 使用 json_decode 将 JSON 字符串转换为 PHP 数组
        $requestBody = json_decode($jsonString, true);
        $roleids = RoleIds::query()->get()->toArray();
        $requestBody['RoleIdList']=$roleids;
        MyLog::info('发送的组装参数'.json_encode($requestBody));
        $row = Server::query()->where('can_push',1)->where("server_id",5)->first();
        $pushUrl = data_get($row,'push_url');
        MyLog::info('发送的接口地址'.json_encode($pushUrl));

        $response = Http::withHeaders(['Content-Type'=>'application/json'])
            ->timeout(5)
            ->post($pushUrl.'/Api/Mail/Add',$requestBody);

        if (PHP_SAPI === 'cli'){
            MyLog::info("邮件发送： " . json_encode($requestBody));
        } else {
            Log::info("邮件发送： " . json_encode($requestBody));
        }

        $body = json_decode($response->body(),true);
        $RetCode = data_get($body,'RetCode');
        MyLog::info('接收消息中'.json_encode($RetCode));
        if ($RetCode == 1000) {
            throw new \Exception('参数错误');
        } else if ($RetCode == 0 ) {
            roleids::query()->delete();
            return ResponseUtil::success();
        } else {
            throw new \Exception('错误代码:' . $RetCode);
        }

    }

    public function import() {
        $file = request()->file('file');

        if (!$file) {
            return response()->json(['code' => 1, 'msg' => '文件未上传']);
        }
        try {
        $filePath = request()->file('file')->store('uploads'); // 保存文件
        $fileContents = file(storage_path('app/' . $filePath)); // 读取文件内容

        // 解析并存储 ID
        $roleIds = [];
        foreach ($fileContents as $line) {
            $roleId = trim($line);
            if (!empty($roleId) && is_numeric($roleId)) {
                $roleIds[] = $roleId;
            }
        }
        MyLog::info('查看提取的ID'.json_encode($roleIds));

        // 批量插入数据库
            RoleIds::query()->delete();

            if (!empty($roleIds)) {
            $insertData = array_map(function($id) {
                return ['Id' => $id];
            }, $roleIds);
            RoleIds::query()->insert($insertData);
        }

            return response()->json(['code' => 0, 'msg' => '角色 ID 导入成功']);
        } catch (\Exception $e) {
            Log::error('角色 ID 上传失败: ' . $e->getMessage());
            return response()->json(['code' => 1, 'msg' => '上传失败，发生错误']);
        }


    }


    }
